<template>
  <div class="flex-column-center-top login-panel br16 pd20 mgl20">
    <div class="text mgt20 fs24">账号登录</div>
    <div class="width-all">
      <el-form ref="formEl" :model="state.formData" :rules="rules" :label-width="80" label-position="left" @keyup.enter="handleLogin">
        <el-form-item label="账户名" prop="username">
          <el-input v-model="state.formData.username" placeholder="请输入账户/手机号" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="state.formData.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>

        <el-form-item />
      </el-form>
      <el-button :loading="state.loading" @click="handleLogin" type="primary" class="width-all mgl5 mgt20">登录</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import type { ElForm } from 'element-plus'
  import request from '@/service'
  import router from '@/router'
  import { Ui, cache } from '@/utils'
  import { initSystemData } from '@/router/hook'
  import { md5 } from 'js-md5'

  const formEl = ref<InstanceType<typeof ElForm> | null>()

  const state = reactive({
    loading: false,
    formData: {
      username: '',
      password: ''
    }
  })

  const rules = {
    username: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
    password: [{ required: true, trigger: 'blur', message: '请输入密码' }]
  }
  /**----------------------------methods----------------------------------------------------------------------- */

  const handleLogin = () => {
    formEl.value?.validate(valide => {
      if (!valide) return
      const params = {
        username: state.formData.username,
        password: md5(state.formData.password)
      }

      state.loading = true

      request
        .post('/auth/login', params)
        .then(async res => {
          if (res.code !== 0) return Ui.useMessage('error', res.msg)
          cache.setToken(res.data)
          /** 初始化系统数据 */
          const data: any = await initSystemData()

          if (data.code !== 0) {
            Ui.useMessage('error', data.msg)
            cache.clear(true)
          } else {
            router.push('/')
          }
        })
        .finally(() => (state.loading = false))
    })
  }
</script>

<style scoped lang="less">
  .login-panel {
    width: 500px;
    height: 610px;
    margin-right: 200px;
    background: #fff;
    .text {
      color: #505355;
      margin-bottom: 100px;
    }
  }
</style>
